package com.smfx.yxt.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smfx.yxt.common.Const;
import com.smfx.yxt.common.MenuConst;
import com.smfx.yxt.common.enums.LeaveStatus;
import com.smfx.yxt.daoSqlserver.AttachmentListMapper;
import com.smfx.yxt.daoSqlserver.TeacherInfoMapper;
import com.smfx.yxt.daoSqlserver.TeacherLeaveMapper;
import com.smfx.yxt.model.TeacherInfo;
import com.smfx.yxt.model.TeacherLeave;
import com.smfx.yxt.page.Page;
import com.smfx.yxt.reqVo.AttachRelationReqVO;
import com.smfx.yxt.reqVo.TeacherLeaveReqVO;
import com.smfx.yxt.service.ITeacherLeaveService;
import com.smfx.yxt.utils.BeanUtils;
import com.smfx.yxt.view.TeacherInfoView;
import com.smfx.yxt.view.TeacherLeaveView;
import com.smfx.yxt.wechat.utils.TemplateUtil;

@Service("teacherLeaveService")
public class TeacherLeaveServiceImpl implements ITeacherLeaveService {

	@Autowired
	private TeacherLeaveMapper teacherLeaveMapper;
	@Autowired
	private AttachmentListMapper attachmentListMapper;
	@Autowired
	private TeacherInfoMapper teacherInfoMapper;
	
	@Override
	public int insertSelective(TeacherLeave record) {
		return teacherLeaveMapper.insertSelective(record);
	}

	@Override
	public TeacherLeave selectByPrimaryKey(Integer id) {
		return teacherLeaveMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(TeacherLeave record) {
		return teacherLeaveMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public List<TeacherLeave> selectListByPage(Page<TeacherLeave> page) {
		return teacherLeaveMapper.selectListByPage(page);
	}

	@Override
	public TeacherLeaveView selectViewById(Integer id) {
		return teacherLeaveMapper.selectViewById(id);
	}

	@Override
	public int insert(TeacherLeaveReqVO reqVO) {
		teacherLeaveMapper.insertSelective(reqVO);
		if(reqVO.getIsAttach() != null) {
			AttachRelationReqVO attach = new AttachRelationReqVO();
			attach.setRelationId(Long.valueOf(reqVO.getId()));
			attach.setAttachIds(reqVO.getIds());
			attachmentListMapper.updateRelationIdByIds(attach);
		}
		new Thread(new TeacherLeaveNoticeExecutor(reqVO)).start();
		return 1;
	}

	@Override
	public int updateAudit(TeacherLeave record) {
		record.setUpdateTime(new Date());
		TeacherLeave baseData = teacherLeaveMapper.selectByPrimaryKey(record.getId());
		boolean isMessage = true;
		if(record.getLeaveStatus().equals(baseData.getLeaveStatus()) || 
				(LeaveStatus.AUDIT_SUCCESS.getCode().equals(baseData.getLeaveStatus())) && 
				record.getLeaveStatus().equals(baseData.getBackStatus())) {
			isMessage = false;
		}
		if(LeaveStatus.AUDIT_SUCCESS.getCode().equals(baseData.getLeaveStatus())){
			record.setBackStatus(record.getLeaveStatus());
			record.setLeaveStatus(null);
			if(LeaveStatus.AUDIT_SUCCESS.getCode().equals(record.getBackStatus())) {
				record.setLeaveDays(baseData.getLeaveDays()-baseData.getBackDays());
			}
		}
		teacherLeaveMapper.updateByPrimaryKeySelective(record);
		if(isMessage) {
			new Thread(new TeacherLeaveNoticeExecutor(record)).start();
		}
		return 1;
	}


	@Override
	public List<TeacherInfo> selectTeacherLeaveCcer(Integer grade) {
		return teacherInfoMapper.selectTeacherLeaveCcer(grade);
	}

	@Override
	public List<TeacherInfo> selectTeacherLeaveApprover(Integer grade) {
		return teacherInfoMapper.selectTeacherLeaveApprover(grade);
	}
	
	class TeacherLeaveNoticeExecutor implements Runnable {
		
		private TeacherLeave leave;
		
		public TeacherLeaveNoticeExecutor(TeacherLeave leave) {
			this.leave = leave;
		}

		@Override
		public void run() {
			try { 
	        		TeacherLeave record = teacherLeaveMapper.selectByPrimaryKey(leave.getId());
					String auditResult = "";
					if(record.getLeaveStatus().equals(LeaveStatus.AUDIT_SUCCESS.getCode())) {
						auditResult = "已批准";
					}else {
						auditResult = "已拒绝：" + record.getRejectReason();
					}
					TeacherInfo teacher = teacherInfoMapper.selectByPrimaryKey(record.getTeacherId());
					String reqUrl = Const.BASEPATH + Const.TEACHER_ROLE + MenuConst.TEACHER_LEAVE + "/detail/" + record.getId();
					String type = StringUtils.isBlank(record.getBackStatus()) ? "请假" : "销假";
					if(LeaveStatus.AUDIT_PENING.getCode().equals(record.getLeaveStatus()) || 
							LeaveStatus.AUDIT_PENING.getCode().equals(record.getBackStatus())){
						String message = "您好，亲爱的" + record.getApprover() + "老师，您接收到了一个"+type+"申请，请查收";
						TeacherInfo approverTeacher = teacherInfoMapper.selectByPrimaryKey(record.getApproverId());
						if(LeaveStatus.AUDIT_PENING.getCode().equals(record.getLeaveStatus())) {
							TemplateUtil.teacherLeaveApplySend(approverTeacher.getOpenid2(), 
									record.getTeacherName(), record.getStartTime(), record.getEndTime(), 
									record.getLeaveReason(), record.getLeaveType(), message,reqUrl);
						}else {
							TemplateUtil.teacherLeaveApplySend(approverTeacher.getOpenid2(), 
									record.getTeacherName(), record.getBackStartDate(), record.getBackEndDate(), 
									"销假申请", record.getLeaveType(), message,reqUrl);
						}
					}else {
						TeacherInfoView view = BeanUtils.copyAs(teacher, TeacherInfoView.class);
						TemplateUtil.leaveAuditSend(teacher.getOpenid2(), "您的"+type+"申请得到批复！", auditResult, record.getApprover(), 
								record.getUpdateTime(), reqUrl);
						if(record.getLeaveStatus().equals(LeaveStatus.AUDIT_SUCCESS.getCode())) {
							reqUrl = Const.BASEPATH + Const.TEACHER_ROLE + MenuConst.TEACHER_LEAVE + "/detail/" + record.getId();
							List<TeacherInfo> list = teacherInfoMapper.selectTeacherLeaveCcer(teacher.getGrade());
							String desc = view.getGradeText() + view.getName();
							for(TeacherInfo teacherInfo : list) {
								TemplateUtil.leaveAuditSend(teacherInfo.getOpenid2(), desc + "老师的"+type+"申请得到批复，请各位办公室人员、教务员、年级领导、科长知悉", auditResult, record.getApprover(), 
										record.getUpdateTime(), reqUrl);
							}
						}
					}
			} catch (Exception e) { 
	            e.printStackTrace(); 
	        }
		}
	}

	@Override
	public boolean isTeacherLeaveApprover(Integer teacherId) {
		return teacherInfoMapper.selectCountTeacherLeaveApprover(teacherId) > 0 ? true : false;
	}

	@Override
	public boolean isTeacherLeaveCcer(Integer teacherId) {
		return teacherInfoMapper.selectCountTeacherLeaveCcer(teacherId) > 0 ? true : false;
	}

}
